package Controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

import Communication.Client;
import Communication.MessageHandle;
import View.ConfigurationView;

/** This class controls and manages the process that Configure the connection to the SQL Server */
public class ConfigurationController   implements Serializable {
	
	
	private static final long serialVersionUID = 42L;
	/**  Required attributes */
	ConfigurationView configView;	
	Client client;
	
	/** Constructor calling to listener class that attached to the process  */
	public ConfigurationController() {
		configView = new ConfigurationView();
		configView.showWindow();
		configView.addConfigListeners(new ConfigListener());
				 		
		}
	
	/**  Inner Listener class */ 
		class ConfigListener implements ActionListener
		{
			LoginController loginController;
			
			/** Handle actions */
			public void actionPerformed(ActionEvent event) {
				
				if (event.getSource() == configView.getOkButton())
				{
					Client client = null;
					try {
						/**  Create A new Client to connect the server upon to send and receive messages*/ 
						client = new Client(configView.getIpField().getText().toString(),Integer.parseInt(configView.getPortField().getText()));
						configView.hideWindow();
						
						loginController = new LoginController(client);
						ArrayList<String> data = new ArrayList<String>();
						data.add(configView.getUserNameField().getText());
						data.add(configView.getDbpasswordField().getText());
						data.add(configView.getIpField().getText());
						
						
                          MessageHandle msg = new MessageHandle(data, MessageHandle.CONFIG, false);
						
                          /**  send to server according to complete the process */			
						client.sendToServer(msg);
					
					
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					
				}
				else if (event.getSource() == configView.getExitButton())
				{
					configView.dispose();										
				}				
			}
		}
		
		
		/**
		 * shows window
		 */
		public void showWindow(){
			configView.showWindow();
		}
		
		/**
		 * hides window
		 */
		public void hideWindow(){
			configView.hideWindow();
		}
}
